/**
 * Created by jazhang on 12/13/13.
 */
var w = 500,
    h = 500;

var colorscale = d3.scale.category10();

//Legend titles abc
var LegendOptions = ['Smartphone', 'Tablet'];

//Data
// This data should not be modified after it is initialized.
var data = [
    [
        {axis: "Email", value: 0.59},
        {axis: "Social Networks", value: 0.56},
        {axis: "Internet Banking", value: 0.42},
        {axis: "News Sportsites", value: 0.34},
        {axis: "Search Engine", value: 0.48},
        {axis: "View Shopping sites", value: 0.64},
        {axis: "Paying Online", value: 0.45}
        //        {axis: "Buy Online", value: 0.05},
        //        {axis: "Stream Music", value: 0.07},
        //        {axis: "Online Gaming", value: 0.12},
        //        {axis: "Navigation", value: 0.27}
        //        {axis: "App connected to TV program", value: 0.03},
        //        {axis: "Offline Gaming", value: 0.12},
        //        {axis: "Photo Video", value: 0.4},
        //        {axis: "Reading", value: 0.03},
        //        {axis: "Listen Music", value: 0.22},
        //        {axis: "Watch TV", value: 0.03},
        //        {axis: "TV Movies Streaming", value: 0.03},
        //        {axis: "Listen Radio", value: 0.07},
        //        {axis: "Sending Money", value: 0.18},
        //        {axis: "Other", value: 0.07},
        //        {axis: "Use less Once week", value: 0.08}
    ],
    [
        {axis: "Email", value: 0.48},
        {axis: "Social Networks", value: 0.41},
        {axis: "Internet Banking", value: 0.27},
        {axis: "News Sportsites", value: 0.28},
        {axis: "Search Engine", value: 0.46},
        {axis: "View Shopping sites", value: 0.29},
        {axis: "Paying Online", value: 0.53}
        //        {axis: "Buy Online", value: 0.14},
        //        {axis: "Stream Music", value: 0.05},
        //        {axis: "Online Gaming", value: 0.19},
        //        {axis: "Navigation", value: 0.14}
        //        {axis: "App connected to TV program", value: 0.06},
        //        {axis: "Offline Gaming", value: 0.24},
        //        {axis: "Photo Video", value: 0.17},
        //        {axis: "Reading", value: 0.15},
        //        {axis: "Listen Music", value: 0.12},
        //        {axis: "Watch TV", value: 0.1},
        //        {axis: "TV Movies Streaming", value: 0.14},
        //        {axis: "Listen Radio", value: 0.06},
        //        {axis: "Sending Money", value: 0.16},
        //        {axis: "Other", value: 0.07},
        //        {axis: "Use less Once week", value: 0.17}
    ]
];

//Options for the Radar chart, other than default
var mycfg = {
    w: w,
    h: h,
    maxValue: 1,
    levels: 5,
    ExtraWidthX: 900,
    densityColors: ["#E54335", "#FED643", "#E4F340", "#A66688", "#AA2266", "#666ADD","#31BCD3", "#3CA2F6", "#9E38F4", "#992FE4"]
};

function generateNewData(origData, newColumns) {
    var newColumnDict = {},
        newData = [];

    newColumns.forEach(function (column, index) {
        newColumnDict[column] = true;
    });

    origData.forEach(function (dataTuple, index) {
        var newDataTuple = [];

        dataTuple.forEach(function (dataItem, index) {
            if (newColumnDict[dataItem.axis]) {
                newDataTuple.push(dataItem);
            }
        });

        newData.push(newDataTuple);
    });

    return newData;
}

function drawBar(barName) {

    var margin = {top: 20, right: 20, bottom: 30, left: 40},
        width = (460 - margin.left - margin.right) / 2,
        height = (300 - margin.top - margin.bottom) / 2;

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(10, "%");

    var barchart = d3.select('#body')
        .selectAll('svg').append("g")
        .attr("id", "barchart")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        //.attr("transform", "rotate(30) translate(" + margin.left + "," + margin.top + ")" );
        .attr("transform", "translate(700, 230)");

    //    d3.tsv("data.tsv", type, function (error, data) {
    x.domain(barData[barName].name);
    y.domain(barData[barName].frequency);

    barchart.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    barchart.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Frequency");

    barchart.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", "bar")
        .attr("x", function (d) {
            return x(d.letter);
        })
        .attr("width", x.rangeBand())
        .attr("y", function (d) {
            return y(d.frequency);
        })
        .attr("height", function (d) {
            return height - y(d.frequency);
        });


}

function type(d) {
    d.frequency = +d.frequency;
    return d;
}

function drawLegend(data) {
    if (!data || data[0].length <= 0) {
        return;
    }
    var svg = d3.select('#body')
        .selectAll('svg')
        .append('svg')
        .attr("width", w + 300)
        .attr("height", h);

    //Create the title for the legend
    var text = svg.append("text")
        .attr("class", "title")
        .attr('transform', 'translate(90,0)')
        .attr("x", w - 70)
        .attr("y", 10)
        .attr("font-size", "12px")
        .attr("fill", "#404040")
        .text("What % of owners use a specific service in a week");

    //Initiate Legend
    var legend = svg.append("g")
        .attr("class", "legend")
        .attr("height", 100)
        .attr("width", 200)
        .attr('transform', 'translate(90,20)');
    //Create colour squares
    legend.selectAll('rect')
        .data(LegendOptions)
        .enter()
        .append("rect")
        .attr("x", w - 65)
        .attr("y", function (d, i) {
            return i * 20;
        })
        .attr("width", 10)
        .attr("height", 10)
        .style("fill", function (d, i) {
            return colorscale(i);
        });
    //Create text next to squares
    legend.selectAll('text')
        .data(LegendOptions)
        .enter()
        .append("text")
        .attr("x", w - 52)
        .attr("y", function (d, i) {
            return i * 20 + 9;
        })
        .attr("font-size", "11px")
        .attr("fill", "#737373")
        .text(function (d) {
            return d;
        });
}

function drawShowColor() {

    var portraitImage = new Image();
    portraitImage.src = "color.png";

    var colorDiv = d3.select('#chart')
            .append("div")
            // .html("High")
            .style("position", "fixed")
            .style("top", "500px")
            .style("left", "1000px")
            .style("font-size", "12px");


    colorDiv.append("span")
        .html("High")
        .style("float", "left")
        .style("padding-right", "5px");

    colorDiv.append("span")
        .html("Low")
        .style("float", "right")
        .style("padding-left", "5px");
    

        colorImage = colorDiv.selectAll("image")
            .data([1])
            .enter()
            .append("image")
            .attr("src", "color.png")
            .attr("width", 300)
            .attr("height", 20);


}

function drawColumnSelector(data) {
    // Create drop down list
    var dataColumns,
        inputDiv,
        inputLabel;

    dataColumns = data[0].map(function (item, index) {
        return item.axis;
    });
    inputDiv = d3.select('#chart')
        .append("div")
        .html("Add or remove columns to chart:<br>")
        .style("position", "fixed")
        .style("top", "47px")
        .style("left", "1000px")
        .style("font-size", "12px");

    inputLabel = inputDiv.selectAll("label")
        .data(dataColumns)
        .enter()
        .append("label");

    inputLabel.append("input")
        .attr("type", "checkbox")
        .attr("value", function (d) {
            return d;
        })
        .attr("name", "columns")
        .attr("checked", true)
        .style("font-size", "12px")
        .on("change", function () {
            var inputCheckBoxes,
                selectedColumns = [],
                newData;

            inputCheckBoxes = inputLabel.selectAll("input");
            inputCheckBoxes.forEach(function (inputCheckBox, index) {
                if (inputCheckBox[0].checked) { // inputCheckBox is an array with only one element
                    selectedColumns.push(inputCheckBox[0].value);
                }
            });
            // for debug
            // var str = "";
            // selectedColumns.forEach(function (column, index) { str += (index > 0) ? ", " + column : column; });
            // console.log(selectedColumns.length + " columns selected: " + str);

            // redraw chart and legend
            newData = generateNewData(data, selectedColumns);
            RadarChart.data = newData;
            RadarChart.draw();
            drawLegend(RadarChart.data);
        });

    inputLabel.append("text")
        .html(function (d) {
            return d + "<br>";
        })
        .style("color", "#404040")
        .style("font-size", "12px")
        .style("padding-right", "5px");

}

//Call function to draw the Radar chart
//Will expect that data is in %'s
RadarChart.chartId = "#chart";
RadarChart.data = data;
RadarChart.options = mycfg;
RadarChart.drawLegendFunction = drawLegend;
RadarChart.drawBarFunction = drawBar;


RadarChart.draw();
drawLegend(RadarChart.data);
drawColumnSelector(RadarChart.data);

drawShowColor();

